/*
*** (C) 2008 UCMai.com ***

Subj: 用户管理
Auth: zhouyongtai
Date: 2011-01-25
*/
var userWins = new Ext.WindowGroup();
var UserCore = function(){
	//获取用以填充下拉框
	var departmentStore = new Ext.data.Store({
		autoLoad:true,
		proxy:new Ext.data.HttpProxy({url:_S_Department_NameList}),
		reader:new Ext.data.JsonReader({
			fields:[{name:'DepartmentID',type:'int'},
				{name:'DepartmentName'}],
			root:'records'
		})
	});
	//Grid列头

	this.gridHeader = [
		{header:'部门',dataIndex:'DepartmentName',width:200},
		{header:'登录名',dataIndex:'LoginName'},
		{header:'电话号码',dataIndex:'Tel'},
		{header:'QQ号码',dataIndex:'QQ'},
		{header:'电子邮箱',dataIndex:'MailAddr'},
		{header:'状态',dataIndex:'LockStatus',renderer:function(value){
			return '<b><font color="'+ c.aLock[value][1] +'">'+ c.aLock[value][0] +'</font></b>'
		}}
	];
	
	//Grid绑定的字段
	this.gridStore = [
		{name:'DepartmentID'},
		{name:'DepartmentName'},
		{name:'sex'},
		{name:'LoginName'},
		{name:'Tel'},
		{name:'QQ'},
		{name:'MailAddr'},
		{name:'UserID'},
		{name:'Remark'},
		{name:'LockStatus'}
	];
	//表单项
	this.formItems = [{
			xtype:'combo',
			store:departmentStore,
			displayField:'DepartmentName',
			valueField:'DepartmentID',
			fieldLabel:'部门',
			name:'DepartmentID',
			hiddenName:'DepartmentID',
			id:'se_o_departmentid',
			mode:'local',
			triggerAction: 'all',
			blankText:'请选择部门',
			emptyText:'选择部门',
			allowBlank:false,
			anchor:'85%',
			editable: false
		},{
			fieldLabel: '登录名',
			id:'se_o_loginname',
			name: 'LoginName',
			anchor:'85%',
			allowBlank:false
		},{
			inputType:'password',
			fieldLabel: '登录密码',
			name: 'LoginPass',
			id:'se_o_loginpass',
			anchor:'85%',
			allowBlank:false
		},{
			xtype:'combo',
			store:genderStore(),
			displayField:'GenderT',
			valueField:'GenderTID',
			fieldLabel:'性别',
			name:'sex',
			hiddenName:'sex',
			id:'se_o_gendertid',
			mode:'local',
			triggerAction: 'all',
			blankText:'请选择性别',
			emptyText:'选择性别',
			allowBlank:false,
			anchor:'85%',
			editable: false
		},{
			fieldLabel: '电话号码',
			name: 'Tel',
			id:'se_o_tel',
			anchor:'85%'
		},{
			fieldLabel: '手机号码',
			name: 'MobileTel',
			id:'se_o_mobiletel',
			anchor:'85%'
		},{
			xtype:'numberfield',
			fieldLabel: 'QQ号码',
			name: 'QQ',
			id:'se_o_oicq',
			anchor:'85%'
		},{
			fieldLabel: '电子邮箱',
			name: 'MailAddr',
			id:'se_o_mailaddr',
			vtype:'email',
			anchor:'85%'
		},{
			xtype:'textarea',
			fieldLabel: '备注',
			name: 'Remark',
			id:'se_o_remark',
			width:200,
			height:40
		},
		{xtype:'hidden',name: 'UserID',id:'UserID'},
		{xtype:'hidden',name: 'a',id:'se_o_cmdid'},
		{xtype:'hidden',name: 'li',id:'se_o_li'},
		{xtype:'hidden',name: 'ln',id:'se_o_ln'},
		{xtype:'hidden',name:'LockStatus',id:'se_o_lockstatus'}
	];

	this.showWindow = function(str){
		//permit();
		this.form = new Ext.FormPanel({
				labelAlign:'left',
				bodyStyle:'padding:5px',
				frame:true,
				labelWidth:60,
				reader : new Ext.data.JsonReader({
					root : 'record',
					success: '@success'
				},this.formReader),
				items:[{
					layout:'form',
					defaultType:'textfield',
					border:false,
					labelSeparator:'：',
					items:this.formItems
				}]
		});
		this.form.getForm().reset();
		//if (!this.window){
		this.window = new Ext.Window({
			xtype:'window',
			buttonAlign : 'right',
			closable:true,
			resizable: false,
			layout:'fit',
			modal: 'true',
			width:350,
			height:370,
			closeAction:'hide',
			plain: true,
			manager:userWins,
			items:[this.form],
			buttons: [{
				id: 'btnSave',
				text: c.bsave,
				handler: save.createDelegate(this,[str]),
				disabled: false
			},{
				text: c.bcancel,
				handler: function(){
					this.window.hide();
				}.createDelegate(this)
			}]
		});
		this.window.on('hide',function(){
			this.form.destroy();
		}.createDelegate(this));
		//}

		//this.window.show(this.getEl());
		this.window.show();
		this.form.findById('se_o_loginname').focus(false,true);
		this.window.setTitle((str)?c.ad():c.md() + " #" + this.getSelectionModel().getSelected().data.UserID);
		if(!str){
			this.form.findById('se_o_loginpass').setDisabled(true);
			/* local mode */
			this.form.getForm().setValues(this.getSelectionModel().getSelected().data);
		}
	};

	//保存资料
	var save = function(str){
		if (!this.form.getForm().isValid()){
			return;
		}
		var selectedId = this.getSelectedIds(this.keyField);
			alert(selectedId);
		if(str){selectedId = 0;}
		if(selectedId>0){
			this.form.findById('se_o_cmdid').setValue(6);
			this.form.findById('UserID').setValue(selectedId);
		}else{
			var pass = this.form.findById('se_o_loginpass').getValue();
			this.form.findById('se_o_cmdid').setValue(5);
		}
		showLoading(c.g(c.e.save),c.loading);
		zyt.ajax(_C_User_S,this.form.getForm().getValues(), function(){
			hideLoading();
			this.window.hide();
			var act = selectedId>0?c.modify:c.add;
			Ext.HandleTip.msg(c.opres,c.item +  act +c.ok);
			this.reload();
		}.createDelegate(this));
	};
	//修改密码表单项
	this.formPassItems=[{
			inputType:'password',
			fieldLabel: '新密码',
			name: 'LoginPass',
			id:'se_o_loginpass',
			anchor:'85%',
			allowBlank:false
		},{
			inputType:'password',
			fieldLabel: '确认密码',
			name: 'NewLoginPass',
			id:'se_o_loginpass2',
			anchor:'85%',
			allowBlank:false
		},
		{xtype:'hidden',name: 'UserID',id:'UserID'},
		{xtype:'hidden',name: 'a',id:'se_o_cmdid'},
		{xtype:'hidden',name: 'li',id:'se_o_li'},
		{xtype:'hidden',name: 'ln',id:'se_o_ln'}
	];
	this.showPassWin = function(){
		zyt.Permit();
		this.form = new Ext.FormPanel({
				labelAlign:'left',
				bodyStyle:'padding:5px',
				frame:true,
				labelWidth:60,
				items:[
					{
						layout:'form',
						defaultType:'textfield',
						border:false,
						labelSeparator:'：',
						items:this.formPassItems
				}]
		});
		this.form.getForm().reset();
		this.window = new Ext.Window({
			xtype:'window',
			title:'修改密码',
			buttonAlign : 'right',
			closable:true,
			resizable: false,
			layout:'fit',
			modal: 'true',
			width:320,
			height:150,
			closeAction:'hide',
			plain: true,
			items:[this.form],
			buttons: [{
				id: 'btnSave',
				text: c.bsave,
				handler: savepass.createDelegate(this),
				disabled: false
			},{
				text: c.bcancel,
				handler: function(){
					this.window.hide();
				}.createDelegate(this)
			}]
		});
		this.window.on('hide',function(){
			this.form.destroy();
		}.createDelegate(this));
		this.window.show();
		this.form.findById('se_o_loginpass').focus(false,true);
	}

	//保存密码
	var savepass = function(){
		if (!this.form.getForm().isValid()){
			return;
		}
		var pass = this.form.findById('se_o_loginpass').getValue();
		var pass2 = this.form.findById('se_o_loginpass2').getValue();
		if(pass!=pass2){
			alertTip('两次输入密码不一致，请确认后重新输入');
			return false;
		}
		var selectedId = this.getSelectedIds(this.keyField);
		this.form.findById('UserID').setValue(selectedId);
		this.form.findById('se_o_cmdid').setValue(8);
		showLoading(c.g(c.e.save),c.loading);
		zyt.ajax(_C_User_S_Pwd,this.form.getForm().getValues(), function(){
			hideLoading();
			this.window.hide();
			var act = c.modify;
			Ext.HandleTip.msg(c.opres,'密码'+ act +c.ok);
			this.reload();
		}.createDelegate(this));
	};
	//查看项
	this.viewItems = [{
			columnWidth:.5,
			layout:'form',
			items:[
				{
					xtype:'textfield',
					fieldLabel: '部门',
					name: 'DepartmentName',
					anchor:'90%',
					readOnly:true
				}
			]
		},{
			columnWidth:.5,
			layout:'form',
			items:[
				{
					xtype:'textfield',
					fieldLabel: '登录名',
					name: 'LoginName',
					anchor:'90%',
					readOnly:true
				}
			]
		},{
			columnWidth:.5,
			layout:'form',
			items:[
				{
					xtype:'textfield',
					fieldLabel: '性别',
					id:'se_o_gender',
					name: 'sex',
					anchor:'90%',
					readOnly:true
				}
			]
		},{
			columnWidth:.5,
			layout:'form',
			items:[
				{
					xtype:'textfield',
					fieldLabel: '电话号码',
					name: 'Tel',
					anchor:'90%',
					readOnly:true
				}
			]
		},{
			columnWidth:.5,
			layout:'form',
			items:[
				{
					xtype:'textfield',
					fieldLabel: '手机号码',
					name: 'MobileTel',
					anchor:'90%',
					readOnly:true
				}
			]
		},{
			columnWidth:.5,
			layout:'form',
			items:[
				{
					xtype:'textfield',
					fieldLabel: 'QQ号码',
					name: 'QQ',
					anchor:'90%',
					readOnly:true
				}
			]
		},{
			columnWidth:.5,
			layout:'form',
			items:[
				{
					xtype:'textfield',
					fieldLabel: '电子邮箱',
					name: 'MailAddr',
					anchor:'90%',
					readOnly:true
				}
			]
		},{
			columnWidth:1,
			layout:'form',
			items:[
				{
					xtype:'textarea',
					fieldLabel: '描述',
					width:320,
					height:100,
					name: 'Remark',
					readOnly:true
				}
			]
		},{
			fieldLabel: '状态',
			name: 'LockStatus',
			anchor: '85%',
			allowBlank: true
		}
	];
	this.showView = function(){
		zyt.Permit();
		this.form = new Ext.FormPanel({
			defaults: {width:400},
			labelAlign:'left',
			bodyStyle:'padding:5px',
			frame:true,
			labelWidth:60,
			reader : new Ext.data.JsonReader({
				root : 'record',
				success: '@success'
			},this.viewReader),
			items:[
				{
					layout:'column',
					border:false,
					labelSeparator:'：',
					items:this.viewItems
			}]
		});
		this.window = new Ext.Window({
			xtype:'window',
			title: c.vd() + " #" + this.getSelectionModel().getSelected().data.LoginName,
			buttonAlign : 'right',
			closable:true,
			resizable: false,
			modal: 'true',
			layout:'fit',
			width:450,
			height:330,
			closeAction:'hide',
			plain: true,
			items:[this.form],
			buttons: [{
				text: c.close,
				handler: function(){
					this.window.hide();
				}.createDelegate(this)
			}]
		});
		this.window.on('hide',function(){
			this.form.destroy();
		}.createDelegate(this));
		this.window.show();

		/* local mode */
		this.form.getForm().setValues(this.getSelectionModel().getSelected().data);
		genderTID = this.form.findById('se_o_gender').getValue();
		for(var i = aGender.length - 1;i >= 0; i--) {
			if(aGender[i][0]==genderTID) {
				this.form.findById('se_o_gender').setValue(aGender[i][1]);
				break;
			}
		}
	}

	var createprofile = function(){
		//permit();
		var selectedId = this.getSelectedIds(this.keyField);
		var ids = '',length= 0,msg = '';
		zyt.confirmEx('生成','用户系统架构',function(){
			if(typeof selectedId == 'number') {
				zyt.ajax(_C_User_Create, {createuserid:selectedId}, function(result){
					result = (result=='')?'系统架构生成成功':'生成用户[' + result.toString() + ']的系统架构时发生错误！';
					Ext.HandleTip.msg('操作结果',result);
				}.createDelegate(this));
			}else{
				ids = selectedId.split(',');
				var len = ids.length;
				for(var i=0;i<len;i++){
					ajaxRequest(_C_User_Create, {createuserid:ids[i]}, function(result){
						msg += (result=='')?'':'生成用户[' + result.toString() + ']的系统架构时发生错误！\n';
					}.createDelegate(this));
				}
				msg = (msg=='')?'系统架构生成成功，共生成' + len.toString() + '个！':msg;
				Ext.HandleTip.msg('操作结果',msg);
			}
		}.createDelegate(this));
	}

	var remove = function(){
		zyt.Permit();
		var delids = this.getSelectedIds(this.keyField);
		var title = "用户" + (Ext.isNumber(delids) ? "（" + this.getSelectionModel().getSelected().data.LoginName + "）" : "");
		zyt.confirmEx(c.del, title,function(){
			zyt.ajax(_C_User_X_Del, {a:4,aid:delids}, function(){
				Ext.HandleTip.msg(c.opres,c.selitem + c.del + c.ok);
				this.reload();
			}.createDelegate(this));
		}.createDelegate(this));
	}

	var lock = function(str){
		zyt.Permit();
		var act=str ? c.lock:c.unlock;
		Ext.MessageBox.confirm(c.info,'您确定要将所选用户'+act,function(btn){
			if(btn=='yes'){
				var delids = this.getSelectedIds(this.keyField);
				zyt.ajax(_C_User_X_Lock, {a:2,aid:delids}, function(){
					Ext.HandleTip.msg('操作结果',c.selitem + act + c.ok);
					this.reload();
				}.createDelegate(this));
			}
		}.createDelegate(this));
	}
	
	var gridreader = new Ext.data.JsonReader({
		totalProperty:'totalProperty',
		root:'records'
	},this.gridStore);

	UserCore.superclass.constructor.call(this, {
		region: 'center',
		store: this.newStore({url:_C_User_X, reader:gridreader}),
		checkbox:true,
		page:true,
		keyField:'UserID',
		viewConfig: {forceFit:true},
		tbar:[{
				id:'btnAdd',
				text:c.add,
				iconCls:'add',
				handler: this.showWindow.createDelegate(this, [true])
			}, '-',{
				id:'btnModify',
				text:c.modify + '资料',
				iconCls:'modify',
				disabled:true,
				handler:this.showWindow.createDelegate(this, [false])
			},'-',{
				id:'btnModifyPass',
				text:c.modify + '密码',
				iconCls:'modify',
				disabled:true,
				handler:this.showPassWin.createDelegate(this)
			},'-',{
				id:'btnDel',
				text:c.del,
				iconCls:'remove',
				disabled:true,
				handler:remove.createDelegate(this)
			},'-',{
				id:'btnLock',
				text:c.lock,
				iconCls:'lock',
				disabled:true,
				handler:lock.createDelegate(this)
			},'-',{
				id:'btnView',
				text : c.view,
				iconCls:'view',
				disabled:true,
				handler:this.showView.createDelegate(this)
			}, '-',{
				id:'btnCreate',
				text:'生成框架',
				iconCls:'user',
				disabled:true,
				handler:createprofile.createDelegate(this, [false])
			}, '-',new Ext.form.TextField({
				id:'con_o_username',
				emptyText:'请输入姓名'
			}),{
				id:'btnSearch',
				text:'搜索',
				iconCls:'search',
				handler:function(){
					var username = Ext.getCmp('con_o_username').getValue();
					var oCondition = {username:username};
					this.reload(oCondition);
				}.createDelegate(this)
		},'-']
	});

	this.getSelectionModel().on('selectionchange', function(){
		var haveselected = this.getSelectedIds(this.keyField);
		if(haveselected!='0'){
			if(typeof haveselected==='number'){
				Ext.getCmp('btnModify').setDisabled(false);
				Ext.getCmp('btnModifyPass').setDisabled(false);
				Ext.getCmp('btnView').setDisabled(false);
			}else{
				Ext.getCmp('btnModify').setDisabled(true);
				Ext.getCmp('btnModifyPass').setDisabled(true);
				Ext.getCmp('btnView').setDisabled(true);
			}
			Ext.getCmp('btnDel').setDisabled(false);
			Ext.getCmp('btnLock').setDisabled(false);
			Ext.getCmp('btnCreate').setDisabled(false);
		}else{
			Ext.getCmp('btnModify').setDisabled(true);
			Ext.getCmp('btnModifyPass').setDisabled(true);
			Ext.getCmp('btnDel').setDisabled(true);
			Ext.getCmp('btnView').setDisabled(true);
			Ext.getCmp('btnLock').setDisabled(true);
			Ext.getCmp('btnCreate').setDisabled(true);
		}
	}.createDelegate(this));
	
	var onContextMenu = function(grid,rowIndex,e){
		e.stopEvent();
		grid.getSelectionModel().selectRow(rowIndex);
		var messageContextMenu = new Ext.menu.Menu({
			id: 'messageContextMenu',
			items : [
			{
				id:'rView',
				text : c.view,
				iconCls:'view',
				handler:this.showView.createDelegate(this)
			},{
				id:'rAdd',
				text : c.add,
				iconCls:'add',
				handler: this.showWindow.createDelegate(this, [true])
			},{
				id:'rModify',
				text : c.modify,
				iconCls:'modify',
				handler:this.showWindow.createDelegate(this, [false])
			},{
				id:'rDel',
				text : c.del,
				iconCls:'remove',
				handler:remove.createDelegate(this)
			}]
		});
		messageContextMenu.showAt(e.getXY());
		e.preventDefault();
	};
	this.on('rowcontextmenu',onContextMenu);

	this.on("rowdblclick", function(grid,rowIndex){
		this.showView(false);
	});
	//返回多记录集时处理方法（例如获取权限值处理功能按钮）
	this.store.on('load',function(){
		var acl = gridreader.jsonData.Acl;
		if(typeof acl!="undefined"){
			var gridTb = this.getTopToolbar();
			if(acl[0].aNew===0){
				//gridTb.items.get(0).hide();
				//gridTb.items.get(1).hide();
				//messageContextMenu.items.get(1).hide();
			}
			if(acl[0].aEdit===0){
				//gridTb.items.get(2).hide();
				//gridTb.items.get(3).hide();
				//messageContextMenu.items.get(2).hide();
			}
			if(acl[0].aDel===0){
				//gridTb.items.get(4).hide();
				//gridTb.items.get(5).hide();
				//messageContextMenu.items.get(3).hide();
			}
		}
	}.createDelegate(this));
};
Ext.extend(UserCore,Ext.ux.grid.GridPanel);